import Vue from 'vue'
import VueRouter from 'vue-router'
import { getToken } from '@/utils/storage'
// 一级路由
const Layout = () => import('@/views/LayOut')
const Login = () => import('@/views/UserLogin')
const Register = () => import('@/views/UserRegister')
const AddHouse = () => import('@/views/AddHouse')
const MapHouse = () => import('@/views/MapHouse')
const CityList = () => import('@/views/CityList')
const HouseDetail = () => import('@/views/HouseDetail')
// 二级路由
const Home = () => import('@/views/SecondHome')
const News = () => import('@/views/SecondNews')
const Search = () => import('@/views/SecondSearch')
const User = () => import('@/views/SecondUser')
const MyStar = () => import('@/views/MyStar')
const MyRent = () => import('@/views/MyRent')
const AddHouseSearch = () => import('@/views/AddHouseSearch')

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/',
      component: Layout,
      redirect: '/home',
      children: [
        {
          path: 'home',
          component: Home
        },
        {
          path: 'search',
          component: Search
        },
        {
          path: 'news',
          component: News
        },
        {
          path: 'user',
          component: User
        }
      ]
    },
    {
      path: '/login',
      component: Login
    },
    {
      path: '/register',
      component: Register
    },
    {
      path: '/star',
      component: MyStar
    },
    {
      path: '/rent',
      component: MyRent
    },
    {
      path: '/map',
      component: MapHouse
    },
    {
      path: '/city',
      component: CityList
    },
    {
      path: '/add/search',
      component: AddHouseSearch
    },
    {
      path: '/add',
      name: 'addhouse',
      component: AddHouse
    },
    {
      path: '/detail/:houses',
      component: HouseDetail
    }
  ]
})

const darkList = ['/add', '/star', '/rent']

router.beforeEach((to, from, next) => {
  const token = getToken()
  if (token) {
    next()
  } else {
    if (darkList.includes(to.path)) {
      next('/login')
    } else {
      next()
    }
  }
})

export default router
